package com.mystyle.le.weekproject.activity;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.mystyle.le.weekproject.R;
import com.mystyle.le.weekproject.adapter.DetialAdapter;
import com.mystyle.le.weekproject.asynctaks.HeadListAsyncTaks;
import com.mystyle.le.weekproject.beans.DetialList;
import com.mystyle.le.weekproject.intentfactbackcall.MyCallBack;
import com.mystyle.le.weekproject.sqlite.DbManager;
import com.mystyle.le.weekproject.sqlite.MySqlite;
import com.mystyle.le.weekproject.utils.ParseJson;
import com.mystyle.le.weekproject.utils.Url;
import com.squareup.picasso.Picasso;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class DetialActivity extends AppCompatActivity {

    private ListView detial_LV;
    private View inflate;
    private ImageView detial_IV;
    private TextView detial_name;
    private TextView detial_author;
    private TextView detial_state;
    private Button detial_read;
    private Button detial_collect;
    private TextView detial_introduction;
    private Button detial_down;
    private Button detial_up;
    private  List<DetialList> detialLists = new ArrayList<>();
    private DetialAdapter detialAdapter;
    private boolean isCheck = false;
    private static MySqlite mySqlite;
    private String sql=null;
    private  String id1 = null;
    private Cursor cursor;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detial);
        //初始化控件
       initView();
        //初始化数据
        initData(inflate);
        //添加到数据库
        initSQLite();
    }

    public static void operatDb(String sql){
        SQLiteDatabase database=mySqlite.getReadableDatabase();
        database.execSQL(sql);
        database.close();
    }
    public static Cursor query(String sql){
        SQLiteDatabase database=mySqlite.getReadableDatabase();
        return database.rawQuery(sql, null);
    }

    /*
    * 添加数据库
    * */
    private void initSQLite() {
        detial_collect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isCheck){
                    detial_collect.setText("添加收藏");
                    detial_collect.setBackgroundColor(Color.RED);
                    Toast.makeText(DetialActivity.this,"取消收藏",Toast.LENGTH_SHORT).show();
                    sql="select * from data where id1='"+id1+"'";
                    cursor = query(sql);
                    if (cursor.moveToNext()){
                        sql = "delete from data where id1 = '"+id1+"'";
                        operatDb(sql);//关闭数据库
                    }
                    isCheck=false;
                    Log.e("BBBBB","===isCheck==="+isCheck);
                }else {

                    if (detialLists!=null&&detialLists.size()>0){
                        for (int i=0;i<detialLists.size();i++){
                            DetialList detialList = detialLists.get(i);
                            id1 = detialList.getId();
                            String name = detialList.getName();
                            String icon = detialList.getIcon();
                            String state = detialList.getState();
                            String ranking = detialList.getRanking();
                            sql="select * from data where id1='"+id1+"'";
                            cursor =query(sql);
                            if (cursor.moveToNext()){
                                isCheck = true;
                                return;
                            }else {
                                detial_collect.setText("取消收藏");
                                detial_collect.setBackgroundColor(Color.GREEN);
                                Toast.makeText(DetialActivity.this,"添加收藏",Toast.LENGTH_SHORT).show();
                                sql = "insert into data(name,ranking,state,id1,icon) values ('"+name+"','"+ranking+"','"+state+"','"+id1+"','"+icon+"')";
                                operatDb(sql);//关闭数据库
                            }
                        }
                    }

                    Log.e("AAAA","==isCheck=="+isCheck);
                }
            }
        });
    }

    /*
    * 初始化数据
    * */
    private void initData(View inflate) {
        Intent intent = getIntent();
        String id = intent.getStringExtra("id");
        String id1 = intent.getStringExtra("id1");
        String boutiques_new = intent.getStringExtra("boutiques_new");
        String boutiques_recommend = intent.getStringExtra("boutiques_recommend");
        String boutiques_hot = intent.getStringExtra("boutiques_hot");
        String seniorityFragment = intent.getStringExtra("SeniorityFragment");
        String detialsoft_id = intent.getStringExtra("detialsoft_id");
        String manager_cuttor = intent.getStringExtra("manager_cuttor");


        getData(manager_cuttor);
        getData(detialsoft_id);
        getData(id);
        getData(id1);
        getData(boutiques_new);
        getData(boutiques_recommend);
        getData(boutiques_hot);
        getData(seniorityFragment);


    }



    /*
    * 下载数据，并展示
    * */
    private void getData(String id) {
        detialAdapter = new DetialAdapter(detialLists, DetialActivity.this);
        new HeadListAsyncTaks(new MyCallBack.HeadListBack() {
            @Override
            public void sendBack(String path) {
                final List<DetialList> lists = ParseJson.parseDetialPath(path);
                if (lists!=null){
                    detialLists.addAll(lists);
                    for (int i =0;i<lists.size();i++){
                        DetialList detialList = lists.get(i);
                        String icon = detialList.getIcon();
                        //下载图片
                        Picasso.with(DetialActivity.this).load(icon).into(detial_IV);
                        //给控件赋值
                        detial_name.setText(detialList.getName());
                        detial_author.setText(detialList.author);
                        detial_state.setText(detialList.getState());
                        detial_introduction.setText(detialList.getIntroduction());
                    }
                    detial_LV.setAdapter(detialAdapter);
                }
            }
        },DetialActivity.this).execute(Url.BOOK_DAIL_URL+id);


          /*
        * ListView每个Item的点击跳转事件
        * */

        detial_LV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (detialLists!=null&&detialLists.size()>0){
                    DetialList detialList = detialLists.get(position);
                    String id1 = detialList.getId();
                    String number = detialList.getNumber();
                    Intent intent = new Intent(DetialActivity.this,ReaderPicActivity.class);
                    intent.putExtra("Read_id1",id1);
                    intent.putExtra("Read_number",number);
                    startActivity(intent);
                }
            }
        });

    }

    /*
    * 初始化布局
    * */
    private void initView() {
        detial_LV = ((ListView) findViewById(R.id.detial_LV));
//        inflate = DetialActivity.this.getLayoutInflater().inflate(R.layout.detial_headlayout, null);
        //初始化头布局
        inflate = LayoutInflater.from(DetialActivity.this).inflate(R.layout.detial_headlayout,null);
        //找控件
        detial_IV = ((ImageView) inflate.findViewById(R.id.detial_IV));
        detial_name = ((TextView) inflate.findViewById(R.id.detial_name));
        detial_author = ((TextView) inflate.findViewById(R.id.detial_author));
        detial_state = ((TextView) inflate.findViewById(R.id.detial_state));
        detial_read = ((Button) inflate.findViewById(R.id.detial_read));//继续阅读
        detial_collect = ((Button) inflate.findViewById(R.id.detial_collect));//收藏
        detial_introduction = ((TextView) inflate.findViewById(R.id.detial_introduction));
        detial_down = ((Button) inflate.findViewById(R.id.detial_down));
        detial_up = ((Button) inflate.findViewById(R.id.detial_up));

        mySqlite = new MySqlite(DetialActivity.this);

        //添加头布局
        detial_LV.addHeaderView(inflate);
    }
}
